import random

from django import http
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from verifications import serializers

class ImageCodeView(APIView):

    def get(self,request,image_code_id):

        #/verifications/imagecodes/" + this.image_code_id + "/
        #生成一个图像验证码,然后保存到redis中,然后将图像验证码图像返回回去就行了
        try:
            text, image_data = captcha.generate_captcha()
        except Exception as e:
            return http.HttpResponse("生成图像验证码出错")

        redis_conn = get_redis_connection("code")
        redis_conn.setex("image_code_%s"%image_code_id,300,text)

        response = http.HttpResponse(image_data)
        response["Content-Type"] = "image/png"

        return response
        pass
    # passContent-Type:application/json

class SendSmsCodeView(GenericAPIView):
    serializer_class = serializers.ImageCodeSerializer

    def get(self,request,mobile):
        #获取可选参数,等会拿到序列表中进行验证
        query_params = request.query_params

        #使用序列器进行校验
        serializer = self.get_serializer(data=query_params)
        serializer.is_valid(raise_exception = True)

        #60秒之内不再发送短信
        redis_conn = get_redis_connection("code")
        if redis_conn.get("send_flag"):
            return Response({"errmsg": "频繁发送"}, status=status.HTTP_400_BAD_REQUEST)

        #生成并发送短信码
        sms_code = "%06d"%random.randint(0,99999)
        print(sms_code)
        # result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # from celery_tasks.send_sms.tasks import Sendsms
        # Sendsms.delay(mobile, sms_code)

        #将短信验证码保存在redis中

        redis_conn.setex("sms_code_%s"%mobile,300,sms_code)
        redis_conn.setex("send_flag",60,True)

        #返回状态
        return Response(status=status.HTTP_200_OK)
        pass
    pass